<template>
  <div class="app-container">
    <el-form label-width="120px" style="width: 75%">
      <el-form-item label="用户名">
        <el-input v-model="user.username"/>
      </el-form-item>

      <div v-if="$route.params === undefined || $route.params.id === undefined">

        <el-form-item label="密码">
          <el-input v-model="user.password"/>
        </el-form-item>

        <el-form-item label="确认密码">
          <el-input v-model="confirmPassword"/>
        </el-form-item>

      </div>

      <el-form-item label="用户类型">
        <el-select v-model="user.role" placeholder="请选择">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="Email">
        <el-input v-model="user.email"/>
      </el-form-item>

      <el-form-item label="TEL">
        <el-input v-model="user.phone"/>
      </el-form-item>

      <el-form-item label="密保问题">
        <el-input v-model="user.question"/>
      </el-form-item>

      <el-form-item label="密保答案">
        <el-input v-model="user.answer"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
import user from '@/api/mall/user'
export default {
  data() {
    return {
      confirmPassword: '',
      user: {},
      roles: [{
        id: 1,
        name: '管理员'
      }, {
        id: 2,
        name: '普通用户'
      }],
      saveBtnDisabled: false
    }
  },
  watch: {
    $route(to, from) {
      console.log('watch $route')
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.getInfo(id)
      } else {
        this.user = {}
      }
    },
    getInfo(id) {
      user.getUser(id)
        .then(response => {
          this.user = response.data.user
        })
    },
    saveOrUpdate() {
      if (!this.user.id) {
        this.saveUser()
      } else {
        this.updateUser()
      }
    },
    updateUser() {
      user.updateUser(this.user)
        .then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.$router.push({ path: '/user/table' })
        })
    },
    saveUser() {
      user.addUser(this.user)
        .then(response => {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.$router.push({ path: '/user/table' })
        })
    }
  }
}
</script>
